<template>
  <div style="margin: 20px 20px">
    <el-tree
      :data="data"
      show-checkbox
      node-key="value"
      ref="treeRef"
      highlight-current
    ></el-tree>
    <el-button :disabled="saveBtnDisabled" type="primary" @click="save">
      保存
    </el-button>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue';
import { ElTree, ElButton, ElMessage } from 'element-plus';
import menu from '@/api/acl/menu';
import role from "@/api/acl/role";
import { useRoute, useRouter } from 'vue-router';
import useCloseTag from "@/hooks/useCloseTag";

const { closeTag } = useCloseTag()
const treeRef = ref<InstanceType<typeof ElTree>>()
// 路由相关
const route = useRoute()
const data = ref([]);
const roleId = ref('');
const saveBtnDisabled = ref(false);

const init = () => {
  if (route.params?.id) {
    roleId.value = route.params.id as string;
    fetchDataById(roleId.value);
  }
};
const fetchDataById = (roleId: string) => {

   // 获取所有的菜单
   menu.listMenuOptions().then((response) => {
      data.value = response.data;
      // 回显角色已拥有的菜单
      role.getRoleMenuIds(roleId)
        .then(({ data }) => {
          const checkedMenuIds = data;
          console.log("勾选权限", checkedMenuIds);
          checkedMenuIds.forEach((menuId) =>
            treeRef.value.setChecked(menuId, true, false)
          );
        })
    });
};

// 监听器
watch(()=>route.params, (to, from) => {
  console.log('路由变化......')
  console.log(to)
  console.log(from)
  init()
},{
  immediate:true
})


const save = () => {
  saveBtnDisabled.value = true;
  const checkedMenuIds: number[] = treeRef.value
      .getCheckedNodes(false, true)
      .map((node: any) => node.value);

  menu.doAssign(roleId.value, checkedMenuIds).then((response) => {
    
      ElMessage({
        type: 'success',
        message: '保存成功',
      });
      closeTag.value()
    
  });
};
</script>